import { useEffect, useState } from 'react';
import { Link, useSearchParams } from 'react-router-dom';
import { FilterIcon, SlidersIcon, CalendarIcon, TagIcon } from 'lucide-react';
import ImageLoader from '../components/UI/ImageLoader';
import Pagination from '../components/UI/Pagination';
import Filter from '../components/UI/Filter';
// Sample insights data
const allInsights = [{
  id: 'nvidia-ai',
  title: 'NVIDIA announces new AI accelerators with 5x performance boost',
  excerpt: 'New hardware aims to address the growing computational demands of large language models',
  image: 'https://images.unsplash.com/photo-1518770660439-4636190af475?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1074&q=80',
  category: 'industry',
  tags: ['ai', 'nvidia', 'hardware'],
  date: '2023-07-25'
}, {
  id: 'apple-event',
  title: 'Apple schedules Spring event, new iPad Pro models expected',
  excerpt: 'The upcoming event may introduce the first OLED iPad Pro and updated Apple Silicon',
  image: 'https://images.unsplash.com/photo-1561154464-82e9adf32764?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=1170&q=80',
  category: 'events',
  tags: ['apple', 'ipad', 'events'],
  date: '2023-07-20'
}, {
  id: 'samsung-fold',
  title: 'Samsung Galaxy Z Fold 5 leaks reveal radical new hinge design',
  excerpt: "New hinge design could eliminate the crease and improve durability in Samsung's next foldable flagship.",
  image: 'https://images.unsplash.com/photo-1610792516307-ea5acd9c3b00?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80',
  category: 'leaks',
  tags: ['samsung', 'mobile', 'foldables'],
  date: '2023-07-17'
}, {
  id: 'intel-raptor',
  title: 'Intel Raptor Lake refresh CPUs get official pricing and release date',
  excerpt: "Intel's 14th generation processors will arrive sooner than expected with modest performance gains.",
  image: 'https://images.unsplash.com/photo-1591799264318-7e6ef8ddb7ea?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1074&q=80',
  category: 'hardware',
  tags: ['intel', 'cpu', 'computing'],
  date: '2023-07-15'
}, {
  id: 'meta-ar',
  title: 'Meta partners with Ray-Ban for next-gen AR glasses',
  excerpt: 'The collaboration aims to bring stylish, consumer-friendly augmented reality glasses to market next year',
  image: 'https://images.unsplash.com/photo-1622979135225-d2ba269cf1ac?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80',
  category: 'ar/vr',
  tags: ['meta', 'ar', 'wearables'],
  date: '2023-07-10'
}, {
  id: 'ai-regulation',
  title: 'EU proposes comprehensive AI regulation framework',
  excerpt: 'New regulations aim to ensure ethical AI development while fostering innovation in the European market',
  image: 'https://images.unsplash.com/photo-1620712943543-bcc4688e7485?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1165&q=80',
  category: 'policy',
  tags: ['ai', 'regulation', 'eu'],
  date: '2023-07-05'
}, {
  id: 'spotify-hifi',
  title: 'Spotify HiFi tier finally launching next quarter',
  excerpt: "After years of delays, Spotify's lossless audio tier is set to compete with Apple Music and Tidal.",
  image: 'https://images.unsplash.com/photo-1611339555312-e607c8352fd7?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1074&q=80',
  category: 'streaming',
  tags: ['spotify', 'audio', 'streaming'],
  date: '2023-07-01'
}, {
  id: 'playstation-vr2',
  title: 'PlayStation VR2 sales exceed expectations despite high price',
  excerpt: "Sony's premium VR headset finds success with hardcore gamers and VR enthusiasts,",
  image: 'https://images.unsplash.com/photo-1622979135240-caa6648190b6?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80',
  category: 'gaming',
  tags: ['playstation', 'vr', 'gaming'],
  date: '2023-06-28'
}];
const Insights = () => {
  const [searchParams, setSearchParams] = useSearchParams();
  const [currentPage, setCurrentPage] = useState(1);
  const [insights, setInsights] = useState(allInsights);
  const [showFilters, setShowFilters] = useState(false);
  const [selectedCategories, setSelectedCategories] = useState<string[]>([]);
  const [selectedTags, setSelectedTags] = useState<string[]>([]);
  const [sortBy, setSortBy] = useState('date');
  const itemsPerPage = 6;
  useEffect(() => {
    document.title = 'Insights & News | TronoraHub';
  }, []);
  const categoryOptions = [{
    id: 'industry',
    label: 'Industry'
  }, {
    id: 'events',
    label: 'Events'
  }, {
    id: 'leaks',
    label: 'Leaks'
  }, {
    id: 'hardware',
    label: 'Hardware'
  }, {
    id: 'ar/vr',
    label: 'AR/VR'
  }, {
    id: 'policy',
    label: 'Policy'
  }, {
    id: 'streaming',
    label: 'Streaming'
  }, {
    id: 'gaming',
    label: 'Gaming'
  }];
  const tagOptions = [{
    id: 'ai',
    label: 'AI'
  }, {
    id: 'nvidia',
    label: 'NVIDIA'
  }, {
    id: 'apple',
    label: 'Apple'
  }, {
    id: 'samsung',
    label: 'Samsung'
  }, {
    id: 'mobile',
    label: 'Mobile'
  }, {
    id: 'intel',
    label: 'Intel'
  }, {
    id: 'cpu',
    label: 'CPU'
  }, {
    id: 'meta',
    label: 'Meta'
  }, {
    id: 'ar',
    label: 'AR'
  }, {
    id: 'vr',
    label: 'VR'
  }, {
    id: 'regulation',
    label: 'Regulation'
  }, {
    id: 'audio',
    label: 'Audio'
  }, {
    id: 'gaming',
    label: 'Gaming'
  }];
  const sortOptions = [{
    id: 'date',
    label: 'Most Recent'
  }, {
    id: 'title',
    label: 'Alphabetical'
  }];
  useEffect(() => {
    // Check for URL parameters
    const tagParam = searchParams.get('tag');
    const categoryParam = searchParams.get('category');
    if (tagParam) {
      setSelectedTags([tagParam.toLowerCase()]);
    }
    if (categoryParam) {
      setSelectedCategories([categoryParam.toLowerCase()]);
    }
  }, [searchParams]);
  useEffect(() => {
    // Apply filters and sorting
    let filteredInsights = [...allInsights];
    // Filter by category
    if (selectedCategories.length > 0) {
      filteredInsights = filteredInsights.filter(insight => selectedCategories.includes(insight.category));
    }
    // Filter by tag
    if (selectedTags.length > 0) {
      filteredInsights = filteredInsights.filter(insight => insight.tags.some(tag => selectedTags.includes(tag)));
    }
    // Apply sorting
    if (sortBy === 'date') {
      filteredInsights.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
    } else if (sortBy === 'title') {
      filteredInsights.sort((a, b) => a.title.localeCompare(b.title));
    }
    setInsights(filteredInsights);
    setCurrentPage(1); // Reset to first page when filters change
  }, [selectedCategories, selectedTags, sortBy]);
  // Get current page items
  const indexOfLastItem = currentPage * itemsPerPage;
  const indexOfFirstItem = indexOfLastItem - itemsPerPage;
  const currentItems = insights.slice(indexOfFirstItem, indexOfLastItem);
  const totalPages = Math.ceil(insights.length / itemsPerPage);
  return <div className="w-full bg-[#0d0d10] pt-24 pb-16">
      <div className="container mx-auto px-4">
        <div className="flex flex-col md:flex-row justify-between items-start md:items-center mb-8">
          <h1 className="text-3xl md:text-4xl font-bold font-display mb-4 md:mb-0">
            Insights & News
          </h1>
          <div className="flex items-center">
            <button onClick={() => setShowFilters(!showFilters)} className="flex items-center px-4 py-2 bg-[#151518] rounded-lg hover:bg-[#1a1a1d] text-sm mr-4">
              <FilterIcon size={16} className="mr-2" />
              Filters
            </button>
            <div className="relative">
              <select value={sortBy} onChange={e => setSortBy(e.target.value)} className="appearance-none bg-[#151518] px-4 py-2 pr-8 rounded-lg text-sm focus:outline-none focus:ring-1 focus:ring-[#4361ee]">
                {sortOptions.map(option => <option key={option.id} value={option.id}>
                    {option.label}
                  </option>)}
              </select>
              <SlidersIcon size={16} className="absolute right-2 top-1/2 transform -translate-y-1/2 pointer-events-none" />
            </div>
          </div>
        </div>
        {showFilters && <div className="mb-8 p-4 bg-[#0f0f12] rounded-lg border border-[#4361ee]/20">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <Filter label="Category" options={categoryOptions} selectedOptions={selectedCategories} onChange={setSelectedCategories} />
              </div>
              <div>
                <Filter label="Tags" options={tagOptions} selectedOptions={selectedTags} onChange={setSelectedTags} />
              </div>
            </div>
          </div>}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {currentItems.map(insight => <Link key={insight.id} to={`/insights/${insight.id}`} className="group card overflow-hidden hover:shadow-lg hover:shadow-[#4361ee]/10 transition-all">
              <div className="aspect-[16/9] relative">
                <ImageLoader src={insight.image} alt={insight.title} className="w-full h-full" />
              </div>
              <div className="p-6">
                <div className="flex items-center justify-between mb-3">
                  <span className="text-xs font-medium px-3 py-1 rounded-full bg-[#151518] text-[#4361ee]">
                    {insight.category.charAt(0).toUpperCase() + insight.category.slice(1)}
                  </span>
                  <div className="flex items-center text-xs text-[#8a8f98]">
                    <CalendarIcon size={12} className="mr-1" />
                    {new Date(insight.date).toLocaleDateString('en-US', {
                  year: 'numeric',
                  month: 'short',
                  day: 'numeric'
                })}
                  </div>
                </div>
                <h3 className="font-display font-bold text-lg mb-2 group-hover:text-[#4361ee] transition-colors line-clamp-2">
                  {insight.title}
                </h3>
                <p className="text-[#8a8f98] text-sm line-clamp-2 mb-4">
                  {insight.excerpt}
                </p>
                <div className="flex items-center">
                  <TagIcon size={14} className="text-[#8a8f98] mr-2" />
                  <div className="flex flex-wrap">
                    {insight.tags.slice(0, 2).map((tag, i) => <span key={i} className="text-xs text-[#8a8f98] mr-2">
                        #{tag}
                      </span>)}
                    {insight.tags.length > 2 && <span className="text-xs text-[#8a8f98]">
                        +{insight.tags.length - 2}
                      </span>}
                  </div>
                </div>
              </div>
            </Link>)}
        </div>
        {insights.length === 0 && <div className="text-center py-16">
            <h3 className="text-xl font-bold mb-2">
              No articles match your filters
            </h3>
            <p className="text-[#8a8f98]">
              Try adjusting your filters to see more results
            </p>
          </div>}
        {insights.length > itemsPerPage && <Pagination currentPage={currentPage} totalPages={totalPages} onPageChange={setCurrentPage} />}
      </div>
    </div>;
};
export default Insights;